package com.petvc.tv

import android.content.Context
import android.os.Handler
import android.os.Looper
import org.json.JSONObject

object HeartbeatManager {
    private var socket: io.socket.client.Socket? = null
    private var heartbeatHandler: Handler? = null
    private var heartbeatRunnable: Runnable? = null

    fun connectAndRegisterDevice(context: Context) {
        android.util.Log.d("PetTV", "[Socket] 开始连接设备")
        val userData = AuthService.getCurrentUser(context) ?: run {
            android.util.Log.e("PetTV", "[Socket] 用户数据为空，无法连接")
            return
        }
        val accessToken = userData.accessToken
        val userId = getUserIdFromToken(accessToken) ?: run {
            android.util.Log.e("PetTV", "[Socket] 无法从token解析user_id")
            return
        }
        val deviceId = DeviceUtils.getDeviceId(context)
        val deviceName = DeviceUtils.getDeviceName()
        val ipAddress = DeviceUtils.getLocalIpAddress() ?: ""
        val deviceMac = DeviceUtils.getMacAddress() ?: ""

        android.util.Log.d("PetTV", "[Socket] 设备信息: deviceId=$deviceId, deviceName=$deviceName, userId=$userId")

        val params = JSONObject().apply {
            put("access_token", accessToken)
            put("user_id", userId)
            put("device_id", deviceId)
            put("device_name", deviceName)
            put("ip_address", ipAddress)
            put("device_mac", deviceMac)
        }
        android.util.Log.d("PetTV", "[Socket] 发送注册设备: $params")

        if (socket == null) {
            android.util.Log.d("PetTV", "[Socket] 创建新的Socket连接")
            socket = io.socket.client.IO.socket(ApiConfig.SOCKET_SERVER_URL)
        }

        socket?.on(io.socket.client.Socket.EVENT_CONNECT) {
            android.util.Log.d("PetTV", "[Socket] 已连接，发送authenticate: $params")
            socket?.emit("authenticate", params)
            startHeartbeat(context)
        }

        socket?.on(io.socket.client.Socket.EVENT_DISCONNECT) {
            android.util.Log.d("PetTV", "[Socket] 连接断开")
        }

        socket?.on(io.socket.client.Socket.EVENT_CONNECT_ERROR) { args ->
            android.util.Log.e("PetTV", "[Socket] 连接错误: ${args.joinToString()}")
        }

        socket?.on("authenticated") { args ->
            android.util.Log.d("PetTV", "[Socket] 认证成功: ${args.joinToString()}")
        }

        socket?.on("authenticate_ack") { args ->
            android.util.Log.d("PetTV", "[Socket] 注册设备收到ack: ${args.joinToString()}")
        }

        socket?.on("error") { args ->
            android.util.Log.e("PetTV", "[Socket] 收到错误: ${args.joinToString()}")
        }

        socket?.on("player_command") { args ->
            android.util.Log.d("PetTV", "[Socket] 收到player_command事件: ${args.joinToString()}")
            var action: String? = null
            try {
                val data = args[0] as JSONObject
                action = data.getString("action")
                android.util.Log.d("PetTV", "[Socket] 解析播放命令: action=$action")
            } catch (e: Exception) {
                android.util.Log.e("PetTV", "[Socket] 解析播放命令异常: ${e.message}", e)
                return@on
            }
            // 切换到主线程执行ExoPlayer操作
            Handler(Looper.getMainLooper()).post {
                if (action == "play") {
                    android.util.Log.d("PetTV", "[Socket] 执行播放命令")
                    ExoPlayerHolder.logExoPlayerStatus()
                    ExoPlayerHolder.exoPlayer?.let { player ->
                        android.util.Log.d("PetTV", "[Socket] ExoPlayer存在，调用play()")
                        player.play()
                        android.util.Log.d("PetTV", "[Socket] play()调用完成")
                        ExoPlayerHolder.logExoPlayerStatus()
                    } ?: run {
                        android.util.Log.e("PetTV", "[Socket] ExoPlayer为null，无法执行播放")
                    }
                } else if (action == "pause") {
                    android.util.Log.d("PetTV", "[Socket] 执行暂停命令")
                    ExoPlayerHolder.logExoPlayerStatus()
                    ExoPlayerHolder.exoPlayer?.let { player ->
                        android.util.Log.d("PetTV", "[Socket] ExoPlayer存在，调用pause()")
                        player.pause()
                        android.util.Log.d("PetTV", "[Socket] pause()调用完成")
                        ExoPlayerHolder.logExoPlayerStatus()
                    } ?: run {
                        android.util.Log.e("PetTV", "[Socket] ExoPlayer为null，无法执行暂停")
                    }
                } else {
                    android.util.Log.w("PetTV", "[Socket] 未知的播放命令: $action")
                }
            }
        }

        android.util.Log.d("PetTV", "[Socket] 开始连接Socket服务器")
        socket?.connect()
    }

    fun startHeartbeat(context: Context) {
        val deviceId = DeviceUtils.getDeviceId(context)
        if (heartbeatHandler == null) {
            heartbeatHandler = Handler(Looper.getMainLooper())
        }
        heartbeatRunnable = object : Runnable {
            override fun run() {
                val isPlaying = ExoPlayerHolder.exoPlayer?.isPlaying ?: false
                val params = JSONObject().apply {
                    put("device_id", deviceId)
                    put("timestamp", System.currentTimeMillis())
                    put("isPlaying", isPlaying)
                }
                android.util.Log.d("PetTV", "[Socket] 发送心跳: $params")
                socket?.emit("heartbeat", params)
                heartbeatHandler?.postDelayed(this, 30_000)
            }
        }
        heartbeatHandler?.post(heartbeatRunnable!!)
    }

    fun stopHeartbeat() {
        android.util.Log.d("PetTV", "[Socket] 停止心跳发送")
        heartbeatRunnable?.let { runnable ->
            heartbeatHandler?.removeCallbacks(runnable)
        }
        heartbeatRunnable = null
        // 断开socket连接
        socket?.disconnect()
        socket = null
    }

    private fun getUserIdFromToken(accessToken: String): String? {
        return try {
            val parts = accessToken.split(".")
            if (parts.size != 3) return null
            val payload = android.util.Base64.decode(parts[1], android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING)
            val json = org.json.JSONObject(String(payload))
            json.optString("user_id", null)
        } catch (e: Exception) {
            null
        }
    }
} 